﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TireService.Data;

namespace TireService.Web.Finance
{
    public partial class EditInvoice : System.Web.UI.Page
    {
        #region Public Properties

        public int InvoiceId
        {
            get
            {
                if (ViewState["_invoiceid"] != null)
                    return (int)ViewState["_invoiceid"];
                else
                    return 0;
            }
            set
            {
                ViewState["_invoiceid"] = value;
            }
        }

        public int InvoiceDetailId
        {
            get
            {
                if (ViewState["_invoicedetailid"] != null)
                    return (int)ViewState["_invoicedetailid"];
                else
                    return 0;
            }
            set
            {
                ViewState["_invoicedetailid"] = value;
            }
        }

        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            TireServiceDB db = new TireServiceDB();

            if (Page.IsPostBack != true)
            {

                // Get invoiceid
                try
                {
                    Invoice invoice = db.GetInvoice(new Guid(Convert.ToString(Request.QueryString["InvoiceGuid"])));

                    this.InvoiceId = invoice.InvoiceId;
                    ChangePrintLink(Convert.ToString(Request.QueryString["InvoiceGuid"]));

                    LoadInvoiceHeader(db, this.InvoiceId);
                }
                catch (Exception)
                {
                    // Nothing - no invoice selected, create new one
                    this.InvoiceId = 0;
                }


            }

            BindInvoiceDetailData(db);
        }

        protected void ChangePrintLink(string InvoiceGuid)
        {
            hlPrintInvoice.NavigateUrl = "http://www.mobilhjulskift.dk/Reports/View/Faktura.aspx?InvoiceGuid=" + InvoiceGuid;
        }

        protected void LoadInvoiceHeader(TireServiceDB db, int InvoiceId)
        {
            Invoice invoice = db.GetInvoice(InvoiceId);

            txtInvoiceDate.Text = invoice.InvoiceDate.ToShortDateString();
            txtDueDate.Text = invoice.DueDate.ToShortDateString();
            lblCustomerIdValue.Text = invoice.CustomerId.ToString();
            lblInvoiceStatusValue.Text = db.GetInvoiceStatusDescription(invoice.InvoiceStatusId);
        }

        protected void BindInvoiceDetailData(TireServiceDB db)
        {
            gvInvoice.DataSource = db.GetInvoiceDetails(this.InvoiceId);
            gvInvoice.DataBind();
        }

        protected void btnSaveInvoice_Click(object sender, EventArgs e)
        {
            try
            {
                TireServiceDB db = new TireServiceDB();

                // Save header
                if (this.InvoiceId != 0)
                {
                    // Update header
                    Invoice invoice = db.GetInvoice(this.InvoiceId);
                    invoice.InvoiceDate = Convert.ToDateTime(txtInvoiceDate.Text);
                    invoice.DueDate = Convert.ToDateTime(txtDueDate.Text);
                }
                else
                {
                    // Error
                    // TODO: Create code for creating a invoice from scratch
                }

                db.SubmitChanges();
            }
            catch (Exception ex)
            {
                if ((ex) is ArgumentException)
                {
                    // User error - arguments not valid - show error message
                    lMessage.Text = ((ArgumentException)ex).Message;
                }
                else
                {
                    // System error - show general error message
                    lMessage.Text = "Fejl opstod - venligst prøv igen";
                }
            }
            finally
            {
                // Update message panel
                upMessage.Update();
            }
        }

        protected void btnSaveInvoiceDetail_Click(object sender, EventArgs e)
        {
            try
            {
                TireServiceDB db = new TireServiceDB();

                if (this.InvoiceDetailId == 0)
                {
                    // Create new line
                    InvoiceDetail invoicedetail = new InvoiceDetail();
                    invoicedetail.InvoiceId = this.InvoiceId;
                    invoicedetail.Description = txtDescription.Text;
                    invoicedetail.Price = Convert.ToDecimal(txtPrice.Text);

                    db.AddInvoiceDetail(invoicedetail);
                }
                else
                {
                    // Edit existing line
                    InvoiceDetail invoicedetail = db.GetInvoiceDetail(this.InvoiceDetailId);

                    invoicedetail.Description = txtDescription.Text;
                    invoicedetail.Price = Convert.ToDecimal(txtPrice.Text);
                }

                // Commit changes to database
                db.SubmitChanges();

                // Clear invoicedetail form
                txtDescription.Text = "";
                txtPrice.Text = "";

                // Bind invoice details data
                BindInvoiceDetailData(db);
            }
            catch (Exception ex)
            {
                if ((ex) is ArgumentException)
                {
                    // User error - arguments not valid - show error message
                    lMessage.Text = ((ArgumentException)ex).Message;
                }
                else
                {
                    // System error - show general error message
                    lMessage.Text = "Fejl opstod - venligst prøv igen";
                }
            }
            finally
            {
                // Update message panel
                upMessage.Update();
            }
        }

        #region GridView Events

        /// <summary>
        /// Gridview function that change field data for unbound fields
        /// </summary>
        protected void gvInvoice_CustomUnboundColumnData(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewColumnDataEventArgs e)
        {
            
        }

        /// <summary>
        /// Gridview function that handles edit selection of invoice lines
        /// </summary>
        protected void gvInvoice_CustomButtonCallback(object sender, DevExpress.Web.ASPxGridView.ASPxGridViewCustomButtonCallbackEventArgs e)
        {
            if (e.ButtonID == "Edit")
            {
                try
                {
                    // Get id and go to editmode
                    this.InvoiceDetailId = Convert.ToInt32(gvInvoice.GetRowValues(e.VisibleIndex, "InvoiceDetailId"));

                    TireServiceDB db = new TireServiceDB();

                    InvoiceDetail invoicedetail = db.GetInvoiceDetail(this.InvoiceDetailId);

                    if (invoicedetail != null)
                    {
                        txtDescription.Text = invoicedetail.Description;
                        txtPrice.Text = invoicedetail.Price.ToString();
                    }
                    else
                    {
                        // Throw error
                    }
                }
                catch (Exception ex)
                {
                    if ((ex) is ArgumentException)
                    {
                        // User error - arguments not valid - show error message
                        lMessage.Text = ((ArgumentException)ex).Message;
                    }
                    else
                    {
                        // System error - show general error message
                        lMessage.Text = "Fejl opstod - venligst prøv igen";
                    }
                }
                finally
                {
                    // Update message panel
                    upMessage.Update();
                }
            }
        }

        /// <summary>
        /// Gridview function that runs when user has confirmed to delete invoiceline 
        /// </summary>
        protected void gvInvoice_RowDeleting(object sender, DevExpress.Web.Data.ASPxDataDeletingEventArgs e)
        {
            // Delete invoiceline
            try
            {
                // Get id
                int id = Convert.ToInt32(e.Keys[0]);

                // reset id
                this.InvoiceDetailId = 0;

                TireServiceDB db = new TireServiceDB();

                InvoiceDetail invoicedetail = db.GetInvoiceDetail(id);

                if (invoicedetail != null)
                {
                    db.RemoveInvoiceDetail(invoicedetail);
                }
                else
                {
                    // Nothing - invoicedetail does not exist
                }

                // Clear invoicedetail form
                txtDescription.Text = "";
                txtPrice.Text = "";

                // Bind invoice details data
                BindInvoiceDetailData(db);

                // Change message
                lMessage.Text = "Linje blev slettet";
            }
            catch (Exception ex)
            {
                if ((ex) is ArgumentException)
                {
                    // User error - arguments not valid - show error message
                    lMessage.Text = ((ArgumentException)ex).Message;
                }
                else
                {
                    // System error - show general error message
                    lMessage.Text = "Fejl opstod - venligst prøv igen";
                }
            }
            finally
            {
                // Update message panel
                upMessage.Update();
            }
        }

        #endregion


    }
}